package week11;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.concurrent.TimeUnit;

public abstract class RedisClientDemo {
    static final JedisPool POOL = new JedisPool("127.0.0.1", 6379);
    static final DistLock DIST_LOCK = new JedisDistLock(POOL, "java.camp.LOCK", "camp");
    public static void main(String[] args) {
        try (Jedis jedis = POOL.getResource()) {
            jedis.set("shoes-inventory", "100");
        }
        Thread[] threads = new Thread[20];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(new BuyShoes());
            threads[i].start();
        }
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try (Jedis jedis = POOL.getResource()) {
            System.out.println(jedis.get("shoes-inventory").equals("80"));
        }
    }

    static class BuyShoes implements Runnable {
        @Override
        public void run() {
            DIST_LOCK.lock();
            try (Jedis jedis = POOL.getResource()) {
                jedis.decr("shoes-inventory");
            } finally {
                DIST_LOCK.unlock();
            }
        }
    }
}
